#ifndef _DATA_H_
#define _DATA_H_

#include <string>
#include <cstring>
#include "cJSON.h"

class Data
{
public:
	Data(cJSON *j = NULL)
	{
		json = j;
	}
	Data(bool b)
	{
		json = b ? cJSON_CreateTrue() : cJSON_CreateFalse();
	}
	Data(const char *s)
	{
		json = cJSON_CreateString(s);
	}
	template<class T> Data(const T & n)
	{
		json = cJSON_CreateNumber((double)n);
	}

	void InitArray()
	{
		json = cJSON_CreateArray();
	}
	void InitObj()
	{
		json = cJSON_CreateObject();
	}
	
	bool Open(const char *name);
	bool Open(const std::string & name)
	{
		return Open(name.c_str());
	}
	bool FOpen(const char *path);
	bool FOpen(const std::string & path)
	{
		return FOpen(path.c_str());
	}
	bool Save(const char *name);
	bool Save(const std::string & name)
	{
		return Save(name.c_str());
	}
	void Close();

	const char* Name() const
	{
		return json->string;
	}
	bool Named(const char *str)
	{
		return !std::strcmp(json->string, str);
	}
	bool Named(const std::string & str)
	{
		return Named(str.c_str());
	}

	int Int() const
	{
		return json->valueint;
	}
	float Float() const
	{
		return (float)json->valuedouble;
	}
	char* CStr() const
	{
		return json->valuestring;
	}

	bool Empty() const
	{
		return !json->child;
	}
	Data Begin() const
	{
		return Data(json->child);
	}
	Data End() const
	{
		return Data();
	}
	operator bool() const
	{
		return json != NULL;
	}
	bool operator==(Data d) const
	{
		return json == d.json;
	}
	bool operator!=(Data d) const
	{
		return !(*this == d);
	}
	Data& operator++()
	{
		json = json->next;
		return *this;
	}
	Data& operator++(int)
	{
		return ++(*this);
	}
	Data& operator=(const Data & d)
	{
		json = d.json;
		return *this;
	}

	Data InsFront(const char *dname, Data d)
	{
		return InsAfter(Data(), dname, d);
	}
	Data InsAfter(Data it, const char *dname, Data d);

private:
	cJSON *json;
};

#endif
